package com.api.rc.service.impl;

import com.alibaba.fastjson.JSON;
import com.api.rc.dao.HostRuleMapper;
import com.api.rc.enums.HostRuleKey;
import com.api.rc.model.HostRule;
import com.api.rc.service.RuleService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author RenQiang
 * @date 2021/7/13
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RuleServiceImpl implements RuleService {
    private final HostRuleMapper hostRuleMapper;

    public RuleServiceImpl(HostRuleMapper hostRuleMapper) {
        this.hostRuleMapper = hostRuleMapper;
    }

    private final String CACHE_HOST_RULE_BY_KEY = "rc:host_rule_by_key";

    @Override
    @Cacheable(value = CACHE_HOST_RULE_BY_KEY, key = "#hostRuleKey.name()")
    public HostRule getHostRuleByKey(HostRuleKey hostRuleKey) {
        HostRule hostRule = new HostRule();
        hostRule.setKey(hostRuleKey);
        return hostRuleMapper.selectOne(hostRule);
    }

    @Override
    @CacheEvict(value = CACHE_HOST_RULE_BY_KEY)
    public void saveOrUpdateRule(HostRuleKey hostRuleKey, Object value) {
        HostRule hostRule = this.getHostRuleByKey(hostRuleKey);
        Date now = new Date();
        if (hostRule == null) {
            hostRule = new HostRule();
            hostRule.setKey(hostRuleKey);
            hostRule.setDesc(hostRuleKey.getDesc());
            hostRule.setCreateTime(now);
            hostRule.setUpdateTime(now);
            hostRule.setValue(JSON.toJSONString(value));
            hostRuleMapper.insert(hostRule);
        } else {
            hostRule.setValue(JSON.toJSONString(value));
            hostRule.setUpdateTime(now);
            hostRuleMapper.updateByPrimaryKey(hostRule);
        }
    }
}
